﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Markup;

namespace TextPlus
{
    public class InlineHyperlinkButton : HyperlinkButton
    {
        public InlineHyperlinkButton()
        {
            DefaultStyleKey = typeof (InlineHyperlinkButton);
        }
    }

    [ContentProperty("Text")]
    public class Link : Inline
    {
        private readonly TextBlockPlus _parent;
        internal HyperlinkButton LinkElement = new HyperlinkButton();

        public static DependencyProperty TextProperty = DependencyProperty.Register("Text", typeof (string),
                                                                                    typeof (Link), new PropertyMetadata(Text_Changed));

        public static DependencyProperty NavigateUriProperty = DependencyProperty.Register("NavigateUri", typeof(Uri),
                                                                                           typeof(Link), null);

        public event RoutedEventHandler Click;

        public Link() : this(null)
        {
        }

        internal Link(TextBlockPlus parent)
        {
            _parent = parent;

            InitializeHyperlinkButton();
        }

        private static void Text_Changed(DependencyObject o, DependencyPropertyChangedEventArgs args)
        {
            ((Link) o).LinkElement.Content = (string)args.NewValue;
        }

        private void InitializeHyperlinkButton()
        {
            LinkElement.Click += delegate { OnClick(); };
            if (null != _parent)
            {
                var styleBinding = new Binding("LinkStyle");
                styleBinding.Source = _parent;
                styleBinding.Mode = BindingMode.OneWay;
                LinkElement.SetBinding(FrameworkElement.StyleProperty, styleBinding);

                var tagBinding = new Binding("Tag");
                tagBinding.Source = _parent;
                tagBinding.Mode = BindingMode.OneWay;
                LinkElement.SetBinding(FrameworkElement.TagProperty, tagBinding);
            }
        }

        internal void OnClick()
        {
            if (Click != null)
                Click(this, new RoutedEventArgs());
        }

        public string Text
        {
            get { return (string) GetValue(TextProperty); }
            set { SetValue(TextProperty, value); }
        }

        public Uri NavigateUri
        {
            get { return (Uri)GetValue(NavigateUriProperty); }
            set { SetValue(NavigateUriProperty, value); }
        }
    }
}